package com.aigc.txt2img.exception;

import com.aigc.txt2img.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = BizException.class)
    public ResponseUtil bizExceptionHandler(HttpServletRequest req, BizException e) {
        log.error("业务发生异常：" + e.getMsg(), e);
        return ResponseUtil.error(e.getCode(), e.getMsg());
    }

    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ResponseUtil paramInvalidExceptionHandler(HttpServletRequest req, BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        return ResponseUtil.error(ExceptionEnum.CLIENT_PARAMS_INVALID.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = NullPointerException.class)
    public ResponseUtil nullPointerExceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("空指针异常：" + e.toString(), e);
        return ResponseUtil.error(ExceptionEnum.CHECK_POINTER_NULL.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseUtil defaultExceptionHandler(HttpServletRequest req, Exception e) {
        log.error("未知错误:" + e.toString(),e);
        return ResponseUtil.error(ExceptionEnum.UNKNOWN.getMessage());
    }


}
